package cn.edu.cqupt.cxcy.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.edu.cqupt.cxcy.dto.AdminImpl;
import cn.edu.cqupt.cxcy.dto.IndexImpl;
import cn.edu.cqupt.cxcy.model.LoginFlag;
import cn.edu.cqupt.cxcy.util.Tools;

/**
 * 登陆 操作
 * @author Dancer-mno
 * @date 2015年10月9日
 */

@WebServlet("/Login")
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		String name  = request.getParameter("username");//用户名
		//System.out.println(name);
		String passw = Tools.getMD5(Tools.getMD5(request.getParameter("password")));//两次MD5加密密码
		String cookie = request.getParameter("cookie");//是否记住登录
		String code = request.getParameter("code"); //验证码
		response.setContentType("text/html;charset=utf-8");
		response.setHeader("pragma","no-cache");
		response.setHeader("cache-control","no-cache");
		PrintWriter out = response.getWriter();
		String back = "";
//		response.sendRedirect(request.getHeader("referer"));
		if(name == null || "".equals(name) ||  passw.equals(Tools.getMD5(""))) {
			back = "用户名或密码不能为空！";
			out.print(back);
			out.flush();
			out.close();
			return;
		}
		HttpSession session = request.getSession(); 
		if(code != null) {
			if (!((String)request.getSession().getAttribute("safecode")).equalsIgnoreCase(code)) { //验证验证码
				session.invalidate();
				back = "验证码错误！";
				out.print(back);
				out.flush();
				out.close();
				return;
			}
		}
		List<Object> list = new ArrayList<>();
		list.add(name);
		list.add(passw);
		List<Object> list2 = new IndexImpl().login(list);
		if(list2 != null && !list2.isEmpty()) {
	        if( new AdminImpl().SessionSelect( name)) {
				back = "注意,该账号已有人登陆！";
//				out.print(back);
//				out.flush();
//				out.close();
//				return;
	        }
			session.setAttribute( "user", list2);
			session.setMaxInactiveInterval(60*20); //session超出时间(秒)
			LoginFlag flag = new LoginFlag();
			flag.setSys_flag(true);
			flag.setSys_nip(getIpAddr( request));
			flag.setSys_sessionId( session.getId());
			flag.setSys_username( name);
		} else {
			back = "用户名或密码不正确！";
			out.print(back);
			out.flush();
			out.close();
			return;
		}
		if(cookie != null) {
			Cookie username = new Cookie("username", name);
			Cookie userpasw = new Cookie("passw", passw);
			// 为两个 Cookies 设置过期日期为 24 小时后
			username.setMaxAge(60*60*24); 
			userpasw.setMaxAge(60*60*24);
			// 在响应头中添加两个 Cookies
			response.addCookie( username);
			response.addCookie( userpasw);
		}
		out.print("<script language='JavaScript'>alert('登陆成功!" + back + "');window.location.href='index'</script>");
		out.flush();
		out.close();
		return;
	}
	
	public String getIpAddr(HttpServletRequest request) {
	    String ip = request.getHeader("x-forwarded-for");
	    if(null == ip || 0 == ip.length() || "unknown".equalsIgnoreCase(ip)) {
	        ip = request.getHeader("Proxy-Client-IP");
	    }
	    if(null == ip || 0 == ip.length() || "unknown".equalsIgnoreCase(ip)) {
	        ip = request.getHeader("WL-Proxy-Client-IP");
	    }
	    if(null == ip || 0 == ip.length() || "unknown".equalsIgnoreCase(ip)) {
	        ip = request.getHeader("X-Real-IP");
	    }
	    if(null == ip || 0 == ip.length() || "unknown".equalsIgnoreCase(ip)) {
	        ip = request.getRemoteAddr();
	    }
	    return ip;
	}
}
